package com.xcf.queue;

/**
 * MyCircularQueue <br>
 * 循环队列的实现
 *
 * @author xiaocf <br>
 * @version 1.0 <br>
 * @date 2020/6/24 20:20 <br>
 */
public class MyCircularQueue<T> {

    private Object[] elements;
    private int frontIndex;
    private int nearIndex;
    private int size;

    public MyCircularQueue() {
        this(16);
    }

    public MyCircularQueue(int capacity) {
        this.elements = new Object[capacity];
        this.frontIndex = 0;
        this.nearIndex = 0;
        this.size = 0;
    }

    /**
     * Insert an element into the circular queue.
     * Return true if the operation is successful.
     */
    public boolean enQueue(T object) {
        if (isFull( )) {
            return false;
        }
        size++;
        elements[nearIndex++] = object;
        if (nearIndex >= elements.length) {
            nearIndex = 0;
        }
        return true;
    }

    /**
     * Delete an element from the circular queue.
     * Return true if the operation is successful.
     */
    public boolean deQueue() {
        if (isEmpty( )) {
            return false;
        }
        size--;
        if (frontIndex >= elements.length - 1) {
            frontIndex = 0;
        } else {
            frontIndex++;
        }
        return true;
    }

    /**
     * Get the front item from the queue.
     */
    public T front() {
        if (isEmpty( )) {
            return null;
        }
        return (T) elements[frontIndex];
    }

    /**
     * Get the last item from the queue.
     */
    public T rear() {
        if (isEmpty( )) {
            return null;
        }
        if (nearIndex == 0) {
            return (T) elements[elements.length - 1];
        }
        return (T) elements[nearIndex - 1];
    }

    /**
     * Checks whether the circular queue is empty or not.
     */
    public boolean isEmpty() {
        return size <= 0;
    }

    /**
     * Checks whether the circular queue is full or not.
     */
    public boolean isFull() {
        return size >= elements.length;
    }

    public static void main(String[] args) {
        MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
        System.out.println(circularQueue.enQueue(1));  // 返回 true
        System.out.println(circularQueue.enQueue(2));  // 返回 true
        System.out.println(circularQueue.enQueue(3));  // 返回 true
        System.out.println(circularQueue.enQueue(4));  // 返回 false，队列已满
        System.out.println(circularQueue.rear( ));  // 返回 3
        System.out.println(circularQueue.isFull( ));  // 返回 true
        System.out.println(circularQueue.deQueue( ));  // 返回 true
        System.out.println(circularQueue.enQueue(4));  // 返回 true
        System.out.println(circularQueue.rear( ));  // 返回 4
    }
}
